import request from '@/utils/request';

const ProductInfoAPI = {
  /**
   * @param {Array<ProductInfo>} data
   * @param {AxiosRequestConfig} options
   * @returns {Promise<ApiResp>}
   */
  insertOrUpdate(data, options = null) {
    return request.post('/product/info/insertOrUpdate', data, options);
  },

  /**
   * @param {String} relationCode
   * @param {String} showContentType
   * @param {String} id
   * @param {AxiosRequestConfig} options
   * @returns {Promise<ApiResp>}
   */
  delete({ relationCode, showContentType, id }, options = null) {
    return request.get('/product/info/delete', { ...options, params: { relationCode, showContentType, id } });
  },

  deleteItems(items, options = null) {
    const relationCode = items[0].relationCode;
    let showContentType = new Set();
    let id = new Set();
    items.forEach((item) => {
      showContentType.add(item.showContentType);
      id.add(item.id);
    });
    showContentType = Array.from(showContentType).join(',');
    id = Array.from(id).join(',');

    return request.get('/product/info/delete', { ...options, params: { relationCode, showContentType, id } });
  },

  /**
   * @param {String} relationCode
   * @param {String} showContentType
   * @param {AxiosRequestConfig} options
   * @returns {Promise<ApiResp<Array<ProductInfo>>>}
   */
  view({ relationCode, showContentType }, options = null) {
    return Promise.all(
      relationCode
        .split(',')
        .map((code) =>
          request
            .get('/product/info/view', { ...options, params: { relationCode: code, showContentType } })
            .catch(() => Promise.resolve({ code: '000', data: [] })),
        ),
    ).then((all) => {
      return Promise.resolve({
        code: '000',
        data: all.flatMap((v) => v.data),
      });
    });
  },
};

export default ProductInfoAPI;
